const db = uniCloud.database()
const dbCmd = db.command;
module.exports = {
	main: async (event) => {
		let {
			res,
			data,
			action
		} = event;
		switch (action) {
			case 'query':
				res = await getData(data);
				break;
			case 'queryById':
				res.data = await getDataById(data);
				break;
			case 'add':
				res = await addData(data);
				break;
			default:
				res = {
					code: 402,
					msg: '非法访问'
				}
				break;
		}
		return res;
	}
}

/**
 * 获取列表数据
 */
async function getData() {
	var res = {}
	let count = await db.collection('coupon_user').where({
		couponId: data.couponId,
		userId: data.userId
	}).count();
	let tmp = {
		index: data.index,
		count: count
	}
	res.data = tmp;
	res.code = 200;
	return res
}
/**
 * 获取数据通过ID
 */
async function getDataById(data) {
	var result = await db.collection('coupon_user').where({
		state: 0, //未使用
		userId: data.userId
	}).get();
	return result.data
}
/**
 * 添加数据
 */
async function addData(data) {
	var res = {}
	//TODO 判断次数超过限制没
	const result = await db.collection('coupon_user').add({
		couponId: data.couponId,
		userId: data.userId,
		state: data.state,
		updatetime: data.updatetime
	})
	res.data = result
	const result2 = await db.collection('coupon').doc(data.couponId).update({
		hasGetTimes: parseInt(data.hasGetTimes) + 1,
		updatetime: data.updatetime
	})

	res.code = 200;
	return res;
}
